<?php
class RegisterController extends AppController {
	public $helpers = array('Html','Form');
	
	public function register() {
		//check login before register
		if($this->Session->check('AdminLogin')) {
			$this->Session->setFlash('Already login!','default',array('class' => 'alert alert-info'));
			return $this->redirect(array('controller' => 'posts', 'action' => 'index'));
		}
		if($this->Session->check('SearchCondition')){
			$this->Session->delete('SearchCondition');
		}
	}
	
	public function doRegister() {
		//validate input
		$this->loadModel('Admin');
		if($this->request->is('post')) {
			$username = $this->request->data['username'];
			$admin = $this->Admin->find('first',array('conditions' => array('Admin.Username' => $username)));
			if($admin) {
				$this->Session->setFlash('Username had been used!!!','default',array('class'=>'alert alert-warning'));
				return $this->render('/register/register');
			}
			$pass = $this->request->data['password'];
			$confirm = $this->request->data['confirmPassword'];
			if($pass != $confirm) {
				$this->Session->setFlash('Confirm password is not correct!!!','default',array('class'=>'alert alert-warning'));
				return $this->render('/register/register');
			}
			//save to db
			$this->Admin->set(array(
				'Username' => $this->request->data['username'],
				'Password' => $this->request->data['password'],
				'Fullname' => $this->request->data['fullname']
			));
			if($this->Admin->save()) {
				$this->Session->setFlash('Register successfully.','default',array('class'=>'alert alert-success'));
				return $this->redirect(array('action' => 'doLoginAfterRegis', $this->request->data['username']));
			}
			$this->Session->setFlash('Register failed!!!','default',array('class'=>'alert alert-warning'));
			return $this->render('/register/register');
		}
	}
	
	public function doLoginAfterRegis($username = null) {
		//check params
		if(!$username) {
			$this->Session->setFlash('Invalid transaction!!!','default',array('class'=>'alert alert-warning'));
			return $this->redirect(array('controller' => 'posts', 'action' => 'index'));
		}
		//initiate session for logged-in
		$this->loadModel('Admin');
		$this->Session->write('AdminLogin',$this->Admin->findByUsername($username));
		return $this->redirect(array('controller' => 'posts', 'action' => 'index'));
	}
}